package com.heima.wemedia.gateway.filter;


import com.heima.wemedia.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;

import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;


@Component
@Order(0)//过滤器顺序
public class AuthorizeFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //统计不被拦截路径
        List<String> url =new ArrayList<>();
        url.add("/login/in");
        url.add("/v2/api-docs");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求地址
        String path = request.getURI().getPath();

        //对不被拦截路径放行
        for (String s : url) {
            if (path.contains(s)){
                return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        Claims claims = AppJwtUtil.getClaimsBody(token);
        try {
            int code = AppJwtUtil.verifyToken(claims);
            if (code==-1||code==0){
                Integer id = (Integer)claims.get("id");

                ServerHttpRequest serverHttpRequest = request.mutate().header("id", id.toString()).build();
                exchange.mutate().request(serverHttpRequest).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }
}
